// apiClient.ts

interface LoginResponse {
  success: boolean;
  message: string;
  user: {
    id: number;
    username: string;
    email: string;
  };
}

interface TestApiResponse {
  success: boolean;
  message: string;
  user_info: {
    id: number;
    username: string;
    email: string;
    is_superuser: boolean;
    is_staff: boolean;
    date_joined: string | null;
  };
}

interface ErrorResponse {
  error: string;
  detail?: string;
}

interface RegisterResponse {
  success: boolean;
  message: string;
  user: {
    id: number;
    username: string;
    email: string;
  };
}

interface ErrorResponse {
  error: string;
}

// ✅ 登录函数
export async function login(
  username: string,
  password: string
): Promise<LoginResponse> {
  const response = await fetch("http://localhost:8000/api/login/", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ username, password }),
    credentials: "include", // ← 关键：包含 Cookie（发送和接收）必须！允许跨域时发送/接收 Cookie（即使同域也建议加上）
  });

  if (!response.ok) {
    const errorData: ErrorResponse = await response.json();
    throw new Error(errorData.error || "Login failed");
  }

  const data: LoginResponse = await response.json();
  console.log("✅ 登录成功:", data);
  return data;
}

// ✅ 测试接口函数（获取当前用户信息）
export async function testApi(): Promise<TestApiResponse> {
  const response = await fetch("http://localhost:8000/api/test/", {
    method: "GET",
    credentials: "include", // ← 关键：携带 Cookie
  });

  if (response.status === 401) {
    const errorData: ErrorResponse = await response.json();
    console.warn("⚠️ 未登录:", errorData.detail);
    throw new Error("请先登录");
  }

  if (!response.ok) {
    throw new Error(`HTTP Error: ${response.status}`);
  }

  const data: TestApiResponse = await response.json();
  console.log("✅ 测试接口返回用户信息:", data);

  // 🖨️ 在前端控制台“打印”用户信息（模拟后端打印效果）
  console.log("=".repeat(50));
  console.log("✅ [前端] 当前登录用户信息:");
  console.log(`   ID: ${data.user_info.id}`);
  console.log(`   Username: ${data.user_info.username}`);
  console.log(`   Email: ${data.user_info.email}`);
  console.log(`   Superuser: ${data.user_info.is_superuser}`);
  console.log(`   Staff: ${data.user_info.is_staff}`);
  console.log("=".repeat(50));

  return data;
}

// ✅ 注销函数（可选）
export async function logout(): Promise<void> {
  const response = await fetch("http://localhost:8000/api/logout/", {
    method: "POST",
    credentials: "include",
  });

  if (!response.ok) {
    throw new Error("Logout failed");
  }

  console.log("✅ 已注销");
}

// ✅ 用户注册函数
export async function register(
  username: string,
  password: string,
  password2: string,
  email: string = ""
): Promise<RegisterResponse> {
  const response = await fetch("http://localhost:8000/api/register/", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      username,
      password,
      password2,
      email,
    }),
    credentials: "include", // 可选（注册一般不需 Cookie）
  });

  if (!response.ok) {
    const errorData: ErrorResponse = await response.json();
    throw new Error(errorData.error || "Registration failed");
  }

  const data: RegisterResponse = await response.json();
  console.log("✅ 注册成功:", data);
  return data;
}

// import { register, login, testApi } from "./apiClient";

// async function demoRegisterAndLogin() {
//   try {
//     // 1. 注册新用户
//     await register("alice", "alice123", "alice123", "alice@example.com");

//     // 2. 登录该用户
//     await login("alice", "alice123");

//     // 3. 调用测试接口验证登录状态
//     const userInfo = await testApi();
//     console.log(
//       "🎉 恭喜！注册并登录成功，当前用户:",
//       userInfo.user_info.username
//     );
//   } catch (err) {
//     console.error("❌ 操作失败:", err.message);
//   }
// }

// demoRegisterAndLogin();
